$(function () {
    $("#jqGrid").Grid({
        url: '../stock/inner/list',
        colModel: [
			{label: 'id', name: 'id', index: 'id', key: true, hidden: true},
			{label: '门店', name: 'branchName', index: 'branch_id', width: 80},
			{label: '员工', name: 'personName', index: 'person_id', width: 80},
			{label: '编码', name: 'code', index: 'code', width: 80},
			{label: '入库日期', name: 'innerDate', index: 'inner_date', width: 80},
			{label: '支出', name: 'expenditure', index: 'expenditure', width: 80},
			{label: '备注', name: 'content', index: 'content', width: 80}]
    });
    
    $(window).resize(function () {
        $("#detailInnerTable").setGridWidth($(window).width() - 450);
    });
    var autoWidth = ($(window).width() - 450) / 13;
    $("#detailInnerTable").Grid({
        datatype: "local",
        data:vm.stockInner.productList,
        cellEdit: true,  //开启表格编辑
        cellsubmit: 'clientArray', //remote代表每次编辑提交后进行服务器保存，clientArray只保存到数据表格不保存到服务器
        height: 250,
        shrinkToFit: false,
        autoScroll:true,//设置水平滚动条
        left:90,
        rowNum:99999,
        page: false,
        rowList: false,
        colModel: [
            {label: 'id', name: 'id', index: 'id', hidden: true},
            {label: 'productId', name: 'productId', index: 'productId', hidden: true},
            {label: '精品名称', name: 'allName',editable: false},
            {label: '单价(元)', name: 'price', editable: true, align: 'center', valign: 'middle',
                editrules: {
                    required: true, custom: true, custom_func: function (value, name) {
                        var regu = "(?!^0*(\\.0{1,2})?$)^\\d{1,10}(\\.\\d{1,2})?$";
                        var re = new RegExp(regu);
                        if (re.test(value)) {
                            return [true, ""];
                        } else {
                            return [false, "指导价格式输入不正确"];
                        }
                    }
                }
            },
            {label: '数量', name: 'num', editable: true, align: 'center', valign: 'middle',
                editrules: {
                    required: true, custom: true, custom_func: function (value, name) {
                        var regu = "^[1-9][0-9]*$";
                        var re = new RegExp(regu);
                        if (re.test(value)) {
                            return [true, ""];
                        } else {
                            $(this).val('');
                            return [false, "数量输入不正确"];
                        }
                    }
                }
            },
            {label: '类型', name: 'topClassifyName',editable: false}
        ],
        beforeEditCell: function (rowid, cellname, v, iRow, iCol) {
            vm.lastEditRow = iRow;
            vm.lastEditCell = iCol;
        },
        beforeSubmitCell:function(rowid, cellname, value, iRow, iCol){
        	for (var i = 0; i < vm.stockInner.productList.length; i++) {
				if(vm.stockInner.productList[i].id==rowid){
					vm.stockInner.productList[i][cellname]=value;
					break;
				}
			}
        }
    });
});

var vm = new Vue({
	el: '#rrapp',
	data: {
        showList: true,
        title: null,
        numRow:1,
        lastEditRow:0,
        lastEditCell:0,
		stockInner: {},
		ruleValidate: {
//			name: [
//				{required: true, message: '名称不能为空', trigger: 'blur'}
//			]
		},
		q: {
		    name: ''
		}
	},
	methods: {
		editBlur:function(rowid,val){
			for (var i = 0; i < vm.stockInner.productList.length; i++) {
				if(vm.stockInner.productList[i].id==rowid){
					vm.stockInner.productList[i][cellname]=value;
					break;
				}
			}
		},
		selectStorage:function(){
			openWindow({
            	type: 2,
                title: "选择仓库",
                area: ['80%', '60%'],
                content: ['../product/storageinfo.html'],
                btn: ['确定', '取消'],
                btn1: function (index,layero) {
                	var selectRowData = window[layero.find('iframe')[0]['name']].getSelectedRowData('#jqGrid');
                	vm.stockInner.storageId=selectRowData.id;
                	vm.stockInner.storageName=selectRowData.name;
                    layer.close(index);
                }
            });
		},
		addCarModel:function(){
			openWindow({
            	type: 2,
                title: "选择车型",
                area: ['80%', '60%'],
                content: ['../product/productbase.html?topClassifyId=boq01'],
                btn: ['确定', '取消'],
                btn1: function (index,layero) {
                	var selectRowData = window[layero.find('iframe')[0]['name']].getSelectedRowData('#jqGrid');
                	if(selectRowData.topClassifyId.indexOf("车辆")>0){
                		selectRowData.topClassifyId="car01";
                		selectRowData.topClassifyName="车辆";
                	}else{
                		selectRowData.topClassifyId="boq01";
                		selectRowData.topClassifyName="精品";
                	}
                	selectRowData.productId=selectRowData.id;
                	selectRowData.vin="";
                	selectRowData.id=vm.numRow;
                	vm.numRow+=1;
                	vm.stockInner.productList.push(selectRowData);
                    layer.close(index);
                    vm.reloadDetail();
                }
            });
		},
		copyCarModel:function(){
			var id = getSelectedRow("#detailInnerTable");
			if (id == null) {
				return;
			}
			var otherData={};
			for (var i = 0; i < vm.stockInner.productList.length; i++) {
				if(vm.stockInner.productList[i].id==id){
					otherData=Object.assign({},vm.stockInner.productList[i]);
					break;
				}
			}
			otherData.id=vm.numRow;
			vm.numRow+=1;
			vm.stockInner.productList.push(otherData);
			vm.reloadDetail();
		},
		delRow:function(){
			var id = getSelectedRow("#detailInnerTable");
			if (id == null) {
				return;
			}
			var otherDataList=[];
			for (var i = 0; i < vm.stockInner.productList.length; i++) {
				if(vm.stockInner.productList[i].id==id){
					continue;
				}
				otherDataList.push(vm.stockInner.productList[i]);
			}
			vm.stockInner.productList=otherDataList;
			vm.reloadDetail();
		},
		query: function () {
			vm.reload();
		},
		add: function () {
			vm.showList = false;
			vm.title = "新增";
			vm.stockInner = {productList:[],storageId:null,storageName:""};
            vm.stockInner.productList = [];
		},
		update: function (event) {
            var id = getSelectedRow("#jqGrid");
			if (id == null) {
				return;
			}
			vm.showList = false;
            vm.title = "修改";
            vm.getInfo(id);
		},
		saveOrUpdate: function (event) {
			$('#detailInnerTable').jqGrid("saveCell", vm.lastEditRow, vm.lastEditCell);
            var url = vm.stockInner.id == null ? "../stock/inner/save" : "../stock/inner/update";
            Ajax.request({
			    url: url,
                params: JSON.stringify(vm.stockInner),
                type: "POST",
			    contentType: "application/json",
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
			});
		},
		del: function (event) {
            var ids = getSelectedRows("#jqGrid");
			if (ids == null){
				return;
			}

			confirm('确定要删除选中的记录？', function () {
                Ajax.request({
				    url: "../stock/inner/delete",
                    params: JSON.stringify(ids),
                    type: "POST",
				    contentType: "application/json",
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
					}
				});
			});
		},
		getInfo: function(id){
            Ajax.request({
                url: "../stockinner/info/"+id,
                async: true,
                successCallback: function (r) {
                    vm.stockInner = r.stockInner;
                }
            });
		},
		reload: function (event) {
			vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
			$("#jqGrid").jqGrid('setGridParam', {
                postData: {'name': vm.q.name},
                page: 1
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');
		},
		reloadDetail:function(){
			$("#detailInnerTable").jqGrid('clearGridData');  //清空表格
            $("#detailInnerTable").jqGrid('setGridParam', {  // 重新加载数据
                datatype: 'local',
                data: vm.stockInner.productList,   //  data 是符合格式要求的需要重新加载的数据
                page: 1
            }).trigger("reloadGrid");
		},
        reloadSearch: function() {
            vm.q = {
                name: ''
            };
            vm.reload();
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        }
	}
});